/*
 * ./socket.c
 * Copyright (C) 2009 alexises
 * 
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <string.h>
#include "socket.h"
#include "error.h"


int init_sock(int port, char* dest, SOCKET* irc_sock)
{
	SOCKET sock;
	SOCKADDR_IN sock_in;
	int error;
	int i = 0;
	hostent* host;

	//initialization of sock
	#if defined (WIN32)
		WSADATA WSAData;
		error = WSAStartup(MAKEWORD(2,2), &WSAData);
		if (error)
		{
			return WIN32_INIT_SOCK_ERROR;
		}
	#endif
	sock = socket(AF_INET, SOCK_STREAM, 0);
	
	//recept ip
	do
	{
		host = gethostbyname(dest);
		i++;
	} while (h_errno == TRY_AGAIN && i != 5);

	//catch errors
	switch (h_errno)
	{
		case TRY_AGAIN:
			return TOO_MANY_DNS_ATTEMPT;
			break;
		case HOST_NOT_FOUND:
			return DNS_HOST_NOT_FOUND;
			break;
		case NO_RECOVERY:
			return DNS_ERROR;
			break;
		case NO_DATA:
			return DNS_NO_IP;
			break;
		default:
			break;
	}
	
	//configure socket
	sock_in.sin_addr.s_addr = inet_addr(host->h_addr_list[0]); 
	sock_in.sin_family =  AF_INET;
	sock_in.sin_port = htons(port);
	
	//connecting
	error = connect(sock, (SOCKADDR*)&sock_in, sizeof(sock_in));
	if (error == SOCKET_ERROR)
	{
		return SOCKET_CONNECT_ERROR;
	}
	
	*irc_sock = sock;
	return 0;
}

int send_msg(SOCKET* sock, char* msg)
{
	int len = strlen(msg);
	if (len > 512)
	{
		return BUFFER_TOO_LONG;
	}
}
